package com.bstek.bdf4.investigate.dao;

import com.bstek.bdf.core.view.DoradoJdbcDao;
import com.bstek.bdf4.investigate.entity.Category;
import com.bstek.bdf4.investigate.entity.Investigate;
import com.bstek.bdf4.investigate.entity.WriteInvestigate;
import com.bstek.dorado.data.provider.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import javax.xml.ws.soap.Addressing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Repository
public class WriteInvestigateDao extends DoradoJdbcDao {
    @Autowired
    private InvestigateJPADao investigateJPADao;
    public void getByPage(Page<WriteInvestigate> page, String title, String name) {
        String sql = "select id, investigate_id, intention,remarks, write_user, write_time from write_investigate where 1 = 1 ";
        List<String> parameters = new ArrayList<>();
        if (StringUtils.isNotBlank(title)) {
            sql += " and title like concat('%',?,'%')";
            parameters.add(title);
        }
        if (StringUtils.isNotBlank(name)) {
            sql += " and name like concat('%',?, '%')";
            parameters.add(name);
        }
        this.pagingQueryDorado(page, sql, parameters.toArray(),new BeanPropertyRowMapper<>(WriteInvestigate.class));
        Collection<WriteInvestigate> entities = page.getEntities();
        for (WriteInvestigate writeInvestigate : entities) {
            if (writeInvestigate.getInvestigateId() != null) {
                Investigate investigate1 = investigateJPADao.findById(writeInvestigate.getInvestigateId()).orElse(null);
                writeInvestigate.setTitle(investigate1.getTitle());
                writeInvestigate.setName(investigate1.getName());
                writeInvestigate.setAuthor(investigate1.getAuthor());
                writeInvestigate.setContent(investigate1.getContent());
                writeInvestigate.setCreateUser(investigate1.getCreateUser());
                writeInvestigate.setCreateTime(investigate1.getCreateTime());
                writeInvestigate.setInvestigateOther(investigate1.getOther());
                writeInvestigate.setCategoryId(investigate1.getCategoryId());
            }
            if (writeInvestigate.getCategoryId() != null) {
                Category category = this.getJdbcTemplate().queryForObject("select id, category_name from category where id = ?", new Object[]{writeInvestigate.getCategoryId()}, new BeanPropertyRowMapper<>(Category.class));
                writeInvestigate.setCategory(category);
            }
        }
    }
}
